package chaoyue.study.servlet;

import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * 使用Socket监听请求
 * 自己实现一个Web服务器
 * 在浏览器中访问 http://127.0.0.1:8080 即通过浏览器和当前服务建立连接，变发送HTTP报文
 * 我们响应给浏览器一段HTML报文，浏览器可以解析并渲染
 */
public class Test1_Socket1 {
    public static void main(String[] args) throws Exception {
        // 启动Socket，监听本机8080端口
        ServerSocket serverSocket = new ServerSocket(8080);
        Socket accept = serverSocket.accept();
        // 获取输入流 并打印
        InputStream inputStream = accept.getInputStream();
        byte[] buf = new byte[1024];
        int len = inputStream.read(buf);
        System.out.print(new String(buf, 0, len));

        // 向浏览器响应HTTP报文
        OutputStream outputStream = accept.getOutputStream();
        // 按照http协议的格式封装一个报文
        String response = "HTTP/1.1 200 OK\r\n" +
                "Content-Length: 39\r\n" +
                "Content-Type: text/html;charset=UTF-8\r\n\r\n" +
                "<h1 style=\"color:red\">hello server!<h1>";
        // 将报文写出给浏览器
        outputStream.write(response.getBytes());
        outputStream.flush();
    }
}
